package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.constant.WeChatConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.result.Result;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * ClassName: UserServiceImpl
 * Package: com.sky.service.impl
 * Description:
 *
 * @Author Dylan_Jun
 * @Create 2024/2/13 11:22
 * @Version 1.0
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private UserMapper userMapper;

    @Override
    public User login(UserLoginDTO userLoginDTO) {
        String openid = getOpenid(userLoginDTO.getCode());
        if (openid == null) {
            log.error("微信登录失败，code无效");
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        //数据库中查找是否存在openid
        User user = userMapper.queryByOpenid(openid);
        if (user == null) {
            //不存在 插入数据库中返回令牌
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insert(user);
        }
        return user;
    }

    private String getOpenid(String code) {
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put(WeChatConstant.WX_LOGIN_APPID, weChatProperties.getAppid());
        paramMap.put(WeChatConstant.WX_LOGIN_SECRET, weChatProperties.getSecret());
        paramMap.put(WeChatConstant.WX_LOGIN_JSCODE, code);
        paramMap.put(WeChatConstant.WX_LOGIN_GRANT_TYPE, WeChatConstant.WX_LOGIN_GRANT_TYPE_VALUE);
        String openid = JSONObject.parseObject(HttpClientUtil.doGet(WeChatConstant.WX_LOGIN_URL, paramMap)).getString(WeChatConstant.WX_LOGIN_OPENID);
        return openid;
    }
}
